import { Command } from '../command.js';
import { Mesh, Object3D } from 'three';
import { Editor } from '../editor.js';

/**
 * @param editor Editor
 * @param object THREE.Object3D
 * @constructor
 */
class MergeMeshCommand extends Command {
	oldMesh:Mesh;
	oldMeshParent:Object3D;
	oldMeshIndex:number;
	oldMesh2:Mesh;
	oldMeshParent2:Object3D;
	oldMeshIndex2:number;
	oldMesh3:Mesh[];
	oldMeshParent3:Object3D[];
	oldMeshIndex3:number[];
	newMesh:Mesh;
	constructor( editor:Editor, mesh:Mesh,mesh2:Mesh,...mesh3:Mesh[] ) {

		super( editor );

		this.type = 'MergeObjectCommand';

		if ( mesh && mesh2 ) {
			this.oldMesh=mesh;
			this.oldMesh2=mesh2;
			this.oldMesh3=mesh3;

			this.oldMeshIndex=mesh.parent.children.indexOf(mesh);
			this.oldMeshIndex2=mesh2.parent.children.indexOf(mesh2);
			this.oldMeshParent=mesh.parent;
			this.oldMeshParent2=mesh.parent;

			this.name = `Merge Object: ${mesh.name}`;
			const meshs=[];
			meshs.push(mesh);
			
			meshs.push(mesh2);
			mesh3.forEach(o=>{
				meshs.push(o);
				this.oldMeshParent3.push(o.parent);
				this.oldMeshIndex3.push(o.parent.children.indexOf(o));
			});
			this.newMesh=this.editor.merge(...meshs);

		}

	}

	execute() {
		
		const index=this.oldMesh.parent.children.indexOf(this.oldMesh);
		this.editor.addObject(this.newMesh,this.oldMesh.parent,index);
		this.oldMesh3.forEach(obj=>{
			this.editor.removeObject(obj);
		});
		this.editor.removeObject(this.oldMesh2);
		this.editor.removeObject(this.oldMesh);
		
	}

	undo() {
		this.editor.removeObject(this.newMesh);
		this.editor.addObject(this.oldMesh,this.oldMeshParent,this.oldMeshIndex);
		this.editor.addObject(this.oldMesh2,this.oldMeshParent,this.oldMeshIndex);
		this.oldMesh3.forEach((obj,i)=>{
			this.editor.addObject(obj,this.oldMeshParent3[i],this.oldMeshIndex3[i]);
		});
		

	}

}

export { MergeMeshCommand };
